<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-tabs v-model="activeTab">
        <el-tab-pane label="企业信息" name="company">
          <!-- 企业信息分组 -->
          <div class="form-section-title">企业信息</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="企业名称" prop="enterpriseName">
                <el-input v-model="formData.enterpriseName" placeholder="请输入客户名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="企业编号" prop="enterpriseCode">
                <el-input
                  v-model="formData.enterpriseCode"
                  placeholder="请输入企业编码"
                  :disabled="formType === 'update'"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="法人" prop="legalPerson">
                <el-input v-model="formData.legalPerson" placeholder="请输入法人姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户类型" prop="customerType">
                <el-select v-model="formData.customerType" placeholder="请选择客户类型">
                  <el-option label="企业客户" value="企业客户" />
                  <el-option label="个人客户" value="个人客户" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户负责人" prop="source">
                <el-select
                  v-model="formData.customerManagerId"
                  placeholder="请选择客户类型"
                  @change="handleCustomerManagerChange"
                >
                  <el-option
                    v-for="item in salesManagers"
                    :key="item.id"
                    :label="item.nickname"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户来源" prop="source">
                <el-input v-model="formData.source" placeholder="请输入客户来源" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户分类" prop="customerCategory">
                <el-input v-model="formData.customerCategory" placeholder="请输入客户分类" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户等级" prop="customerLevel">
                <el-input v-model="formData.customerLevel" placeholder="请输入客户等级" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="优先比例%" prop="priorityPercent">
                <el-input-number
                  v-model="formData.priorityPercent"
                  :min="0"
                  :max="100"
                  placeholder="0.00"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="税率%" prop="taxPercent">
                <el-input-number
                  v-model="formData.taxPercent"
                  :min="0"
                  :max="100"
                  placeholder="0.00"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="网址" prop="website">
                <el-input v-model="formData.website" placeholder="请输入客户网站地址" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="传真" prop="fax">
                <el-input v-model="formData.fax" placeholder="请输入传真号码" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="注册资金" prop="registeredCapital">
                <el-input v-model="formData.registeredCapital" placeholder="请输入注册资金" />
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 银行信息分组 -->
          <div class="form-section-title">银行信息</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="开户行" prop="bankName">
                <el-input v-model="formData.bankName" placeholder="请输入开户行信息" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开户账号" prop="bankAccount">
                <el-input v-model="formData.bankAccount" placeholder="请输入开户账号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮编" prop="zipCode">
                <el-input v-model="formData.zipCode" placeholder="请输入邮编" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="地址" prop="Bankaddress">
                <el-input v-model="formData.Bankaddress" placeholder="请输入地址" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="年纳税额" prop="annualTax">
                <el-input v-model="formData.annualTax" placeholder="请输入年纳税额" />
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 客户描述分组 -->
          <div class="form-section-title">客户描述</div>
          <el-form-item label="客户描述" prop="customerDescription">
            <el-input
              type="textarea"
              v-model="formData.customerDescription"
              :maxlength="140"
              show-word-limit
              placeholder="请输入客户描述"
              :rows="4"
            />
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="是否启用" prop="isEnabled">
                <el-switch v-model="formData.isEnabled" active-text="ON" inactive-text="OFF" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="排序值" prop="sort">
                <el-input-number
                  v-model="formData.sort"
                  :min="1"
                  placeholder="1"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="联系人信息" name="contacts">
          <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="联系人" prop="contactPerson" required>
                  <el-input v-model="formData.contactPerson" placeholder="请输入联系人姓名" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="手机号" prop="mobileNumber" required>
                  <el-input v-model="formData.mobileNumber" placeholder="请输入手机号码" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="客户地址" prop="address" required>
                  <el-input v-model="formData.address" placeholder="请输入客户地址" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="邮箱" prop="contactEmail">
                  <el-input v-model="formData.contactEmail" placeholder="请输入邮箱地址" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item>
              <el-button type="primary" @click="submitForm">保存</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确定</el-button>
      <el-button @click="dialogVisible = false">取消</el-button>
    </template>

    <!-- 联系人信息 弹窗 -->
    <!-- <el-dialog v-model="showVisible" title="选择客户负责人" :before-close="handleClose" >
      <CustomerManager/>
      <template #footer>
        <div class="dialog-footer" style="border: none">
          <el-button type="primary" @click="showVisible = false"> Confirm </el-button>
        </div>
      </template>
    </el-dialog> -->
  </Dialog>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ContractInfoApi, ContractInfoVO } from '@/api/customer/contractinfo'
import { getSalesManager } from '@/api/system/user'
import { UserVO } from '@/api/system/user'
import CustomerManager from './CustomerManager.vue'
const handleFocus = () => {
  showVisible.value = true
}

const showVisible = ref(false)
const handleClose = () => {
  showVisible.value = false
}

/** 客户管理 表单 */
defineOptions({ name: 'ContractInfoForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const activeTab = ref('company')
const formRef = ref() // 表单 Ref
const salesManagers = ref<UserVO[]>([])

const formData = ref({
  customerManagerId: undefined,
  id: undefined,
  Bankaddress: undefined,
  enterpriseCode: undefined,
  enterpriseName: undefined,
  source: undefined,
  customerCategory: undefined,
  customerLevel: undefined,
  contactPerson: undefined,
  mobileNumber: undefined,
  customerManager: undefined,
  customerDescription: undefined,
  contractAmount: undefined,
  initialReceivable: undefined,
  initialReceivableBalance: undefined,
  receivableAmount: undefined,
  receivedAmount: undefined,
  receivableBalance: undefined,
  advancePayment: undefined,
  creationTime: undefined,
  isEnabled: undefined,
  operationDescription: undefined,
  legalPerson: undefined,
  customerType: undefined,
  priorityPercent: undefined,
  taxPercent: undefined,
  website: undefined,
  fax: undefined,
  registeredCapital: undefined,
  bankName: undefined,
  bankAccount: undefined,
  zipCode: undefined,
  address: undefined,
  annualTax: undefined,
  sort: undefined,
  email: undefined,
  position: undefined,
  contactRemark: undefined,
  contacts: [],
  contactName: '',
  contactMobile: '',
  contactAddress: '',
  contactEmail: ''
})
const formRules = reactive({
  enterpriseCode: [
    { required: true, message: '企业的唯一标识码，用于区分不同客户不能为空', trigger: 'blur' }
  ],
  enterpriseName: [{ required: true, message: '企业的全称或常用名称不能为空', trigger: 'blur' }],
  creationTime: [
    {
      required: true,
      message: '记录创建的具体时间（年-月-日 时:分:秒），默认为当前时间不能为空',
      trigger: 'blur'
    }
  ],
  isEnabled: [
    {
      required: true,
      message:
        '布尔值，表示该记录是否处于启用状态（如 TRUE 表示启用，FALSE 表示停用），默认为 TRUE不能为空',
      trigger: 'blur'
    }
  ]
})

/** 打开弹窗 */
const open = async (type: string, row?: any) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  activeTab.value = 'company'
  resetForm()
  try {
    formLoading.value = true
    const res = await getSalesManager() // 调用接口获取数据
    salesManagers.value = res // 赋值给销售经理列表
  } finally {
    formLoading.value = false
  }
  // 修改时，设置数据
  if (row) {
    formData.value = { ...formData.value, ...row }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ContractInfoVO
    if (formType.value === 'create') {
      await ContractInfoApi.createContractInfo(data)
      message.success(t('common.createSuccess'))
    } else {
      await ContractInfoApi.updateContractInfo(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const handleCustomerManagerChange = (selectedId: number | undefined) => {
  if (selectedId === undefined) {
    formData.value.customerManager = undefined
    return
  }
  // 查找匹配的销售经理
  const manager = salesManagers.value.find((item) => item.id === selectedId)
  // 将昵称赋值到customerManager字段
  formData.value.customerManager = manager?.nickname
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    customerManagerId: undefined,
    id: undefined,
    enterpriseCode: undefined,
    enterpriseName: undefined,
    source: undefined,
    customerCategory: undefined,
    customerLevel: undefined,
    contactPerson: undefined,
    mobileNumber: undefined,
    customerManager: undefined,
    customerDescription: undefined,
    contractAmount: undefined,
    initialReceivable: undefined,
    initialReceivableBalance: undefined,
    receivableAmount: undefined,
    receivedAmount: undefined,
    receivableBalance: undefined,
    advancePayment: undefined,
    creationTime: undefined,
    isEnabled: undefined,
    operationDescription: undefined,
    legalPerson: undefined,
    customerType: undefined,
    priorityPercent: undefined,
    taxPercent: undefined,
    website: undefined,
    fax: undefined,
    registeredCapital: undefined,
    bankName: undefined,
    bankAccount: undefined,
    zipCode: undefined,
    address: undefined,
    annualTax: undefined,
    sort: undefined,
    email: undefined,
    position: undefined,
    contactRemark: undefined,
    contacts: [],
    contactName: '',
    contactMobile: '',
    contactAddress: '',
    contactEmail: ''
  }
  formRef.value?.resetFields()
}
</script>

<style scoped>
.form-section-title {
  margin: 18px 0 8px;
  font-size: 15px;
  font-weight: bold;
}
</style>
